
<!--
 * @Author: Bennty
 * @Date: 2024-07-16 09:15:44
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-10-24 09:27:55
 * @Description: 请填写简介
-->
<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div class="search">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                    <el-form-item label="签约日期" prop="signDate">
                        <el-col :span="11">
                            <el-date-picker v-model="queryParams.signDateStart" type="date"
                                placeholder="开始时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                            />
                        </el-col>
                        <el-col :span="2" class="text-center">
                            <span>至</span>
                        </el-col>
                        <el-col :span="11">
                            <el-date-picker v-model="queryParams.signDateEnd" type="date"
                                placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                            />
                        </el-col>
                    </el-form-item>
                    <el-form-item label="客户" prop="customerId">
                        <el-select v-model="queryParams.customerId" filterable>
                            <el-option v-for="item in customerList" :label="item.customerName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务员" prop="personName">
                        <el-select v-model="queryParams.personName" filterable>
                            <el-option v-for="user in roleKeyUserList" :key="user.userId" :label="user.userName" :value="user.userName"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="押金抵扣" prop="deduction">
                        <el-select v-model="queryParams.deduction" filterable>
                            <el-option label="全部" value="1"></el-option>
                            <el-option label="部分抵扣" value="2"></el-option>
                            <el-option label="未抵扣" value="3"></el-option>
                            <el-option label="已抵扣" value="4"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="合同完结" prop="status">
                        <el-select v-model="queryParams.status" filterable>
                            <el-option label="全部" value="1"></el-option>
                            <el-option label="未完结" value="3"></el-option>
                            <el-option label="已完结" value="3"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="8" class="mb8">
                    <el-col class="header-button-container" :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleClickAdd">新增</el-button>
                    </el-col>
                    <el-col :offset="1" class="header-button-container" :span="6">
                        <p class="contract-info"> {{`合同总额: ${ totalInfo.total } | 合同余额: ${ totalInfo.surplus } | 押金总额: ${ totalInfo.deposit }`}} </p>
                    </el-col>
                </el-row>
            </template>
            <el-table v-loading="loading" :data="contractList" highlight-current-row @current-change="handleCurrentChange">
                <el-table-column label="签约时间" prop="signDate" align="center" width="160"></el-table-column>
                <el-table-column label="客户" prop="customerName" align="center"></el-table-column>
                <el-table-column label="负责人" prop="businessName" align="center"></el-table-column>
                <el-table-column label="合同总额度" align="center">
                    <template #default="scope">
                        <span>{{ `￥${scope.row.contractAmount}` }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="合同剩余额度" align="center">
                    <template #default="scope">
                        <span>{{ `￥${scope.row.contractSurplusAmount || 0}` }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="押金" align="center">
                    <template #default="scope">
                        <span>{{ `￥${scope.row.contractDeposit}` }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="剩余押金" align="center">
                    <template #default="scope">
                        <span>{{ `￥${scope.row.contractDeposit - scope.row.paidContractAmount}` }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="审批状态" align="center">
                    <template #default="scope">
                        <span class="approved" v-if="scope.row.approvalStatus == '0'">未审批</span>
                        <span class="unapproved" v-else-if="scope.row.approvalStatus == '1'">已通过</span>
                        <span class="unapproved-reject" v-else-if="scope.row.approvalStatus == '2'">已拒绝</span>
                    </template>
                </el-table-column>
                <el-table-column label="抵扣状态" align="center">
                    <template #default="scope">
                        <span class="deduction-none" v-if="scope.row.deductionStatus == '0'">未抵扣</span>
                        <span class="deduction-part" v-else-if="scope.row.deductionStatus == '1'">部分抵扣</span>
                        <span class="deduction-all" v-else-if="scope.row.deductionStatus == '2'">已抵扣</span>
                    </template>
                </el-table-column>
                <el-table-column label="完结状态" align="center">
                    <template #default="scope">
                        <span class="completed" v-if="scope.row.overFlag == '1'">已完结</span>
                        <span class="uncompleted" v-else>已完结</span>
                    </template>
                </el-table-column>
                <el-table-column label="审核状态">
                    <template #default="scope">
                        <el-button class="unexamined" link v-if="scope.row.reviewStatus == '0'" @click="handleClickexamine(scope.row)">未审核</el-button>
                        <el-button class="examined-saler" link v-if="scope.row.reviewStatus == '1'" @click="handleClickexamine(scope.row)">销售审核中</el-button>
                        <el-button class="examined-saler" link v-if="scope.row.reviewStatus == '2'" @click="handleClickFinance(scope.row)">销售审核完成</el-button>
                        <!-- <el-button class="examined-finance" link v-if="scope.row.examineStatus == 2">财务审核</el-button> -->
                        <!-- <span class="unexamined" v-if="scope.row.examineStatus == 0">未审核</span> -->
                        <!-- <span class="examined-saler" v-if="scope.row.examineStatus == 1">销售审核</span> -->
                        <span class="examined-finance" v-if="scope.row.reviewStatus == '3'">财务审核中</span>
                        <span class="examined-finance" v-if="scope.row.reviewStatus == '4'">财务审核完成</span>
                    </template>
                </el-table-column>
                <el-table-column label="备注" prop="remark"></el-table-column>
                <el-table-column label="操作" width="190">
                    <template #default="scope">
                        <div class="operation">
                            <el-tooltip content="编辑" placement="top">
                                <el-button link type="success" :style="{fontSize:'16px'}"  icon="Edit" @click="handleClickEdit(scope.row)" ></el-button>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <el-button link type="danger" :style="{fontSize:'16px'}"  icon="Delete" @click="handleClickDelete(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="详情" placement="top">
                                <el-button link type="warning" :style="{fontSize:'16px'}"  icon="Download" @click="handleClickCheck(scope.row)" ></el-button>
                            </el-tooltip>
                            <el-tooltip content="审批" placement="top">
                                <el-button link type="warning" :style="{fontSize:'16px'}"  icon="Document" @click="handleClickApproval(scope.row)"></el-button>
                            </el-tooltip>
                            
                            <el-tooltip content="退还定金申请" placement="top">
                                <el-button link type="success" :style="{fontSize:'16px'}"  icon="Back" @click="handleClickRefund(scope.row)" ></el-button>
                            </el-tooltip>
                            <el-tooltip content="撤销审核" placement="top">
                                <el-button link type="primary" :style="{fontSize:'16px',margin:'0'}"  icon="TopLeft" @click="handleClickRevoke(scope.row)" ></el-button>
                            </el-tooltip>
                            <el-tooltip content="合同完结" placement="top">
                                <el-button link type="primary" :style="{fontSize:'16px'}"  icon="User" @click="handleClickComplete(scope.row)" ></el-button>
                            </el-tooltip>
                            <el-tooltip content="撤销审批" placement="top">
                                <el-button link type="danger" :style="{fontSize:'16px'}"  icon="Close" @click="handleRevokeApprove(scope.row)"></el-button>
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="totalData > 0" :total="totalData" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                @pagination="getContracts" />
        </el-card>
        <addContract :visible="addDialogVisible" :customers="customerList" @submit="handleSubmitAdd" @close="handleCancelAdd"/>
        <editContract :visible="editDialogVisible" :data="editData" :customers="customerList" @submit="handleSubmitEdit" @close="handleCancelEdit"/>
        <contractDetails :visible="checkDialogVisible" :data="contractDetail" @close="handleCancelCheck" />
        <refundDeposit :visible="refundDialogVisible" :data="contractDetail" @submit="handleSubmitRefund" @close="handleCancelRefund" />
        <examineContract :visible="examineDialogVisible" :data="contractDetail" :account="collection_account" :store="store_name" @submit="handleSubmitExamine" @close="handleCancelexamine"/>
        <financeExamine :visible="financeDialogVisible" :data="contractDetail" :examineData="examineList" @submit="handleSbumitFinance" @close="handleCancelFinance" />
        <approvalContract :visible="approvalDialogVisible"  :data="contractDetail" @submit="handleSubmitApproval" @close="handleCancelApproval" />
    </div>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus';
import useCRMStore from '@/store/modules/crm';
import { getContractApi,deleteContractApi,getContractDetailsApi,completeContractDetailsApi, getExaminesRecordByIdApi, revokeExamineApi, approveContractDetailsApi } from '@/api/sj/contract-crm/index';
import { getCustomerApi } from '@/api/sj/customer-crm/index';
import { contractVo } from '@/api/sj/contract-crm/types';
import { CustomerVO } from '@/api/sj/customer-crm/types';
import addContract from './components/addContract.vue';
import editContract from './components/editContract.vue';
import contractDetails from './components/contractDetails.vue';
import refundDeposit from './components/refundDeposit.vue';
import examineContract from './components/examineContract.vue';
import financeExamine from './components/financeExamine.vue';
import approvalContract from './components/approvalContract.vue';
import useUserStore from '@/store/modules/user';


const queryFormRef = ref<FormInstance>();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { collection_account,store_name } = toRefs<any>(proxy?.useDict('collection_account','store_name'));
const loading = ref(false);
const contractList = ref<contractVo[]>([]);
const currentRow = ref();
const customerList = ref<CustomerVO[]>([]);
const data = reactive({
    queryParams:{
        pageNum: 1,
        pageSize: 30,
        signDateStart: undefined,
        signDateEnd: undefined,
        customerId: undefined,
        personName: undefined,
        deduction: undefined,
        status: undefined
    }
});
const totalInfo = ref({
    total:0,
    surplus:0,
    deposit: 0
});
const { queryParams } = toRefs(data);
const { getUserListByRoleKey } = useCRMStore();
const { roleKeyUserList } = toRefs(useCRMStore());
const totalData = ref(0);
const addDialogVisible = ref(false); 
const editDialogVisible = ref(false);
const editData = ref<contractVo>({});
const checkDialogVisible = ref(false);
const contractDetail = ref<any>();
const refundDialogVisible = ref(false);
const examineDialogVisible = ref(false);
const examineList = ref<any[]>([]);
const financeDialogVisible = ref(false);
const approvalDialogVisible = ref(false);
const store = useUserStore();


/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
};

const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};

const getCustomers = async ()=>{
    const customerParams = {
        pageNum: 1,
        pageSize: 999,
    }
    const { rows } = await getCustomerApi(customerParams);
    customerList.value = rows;
};

/** 获取合同信息 */
const getContracts = async ()=>{
    loading.value = true;
    const result = await getContractApi(queryParams.value);
    contractList.value = result.data.dataPage.records;
    totalInfo.value.total = result.data.contractAmount;
    totalInfo.value.deposit = result.data.depositAmount;
    totalInfo.value.surplus = result.data.contractBalance;
    totalData.value = result.data.dataPage.total;
    loading.value = false;
};

/** 根据id获取合同信息 */
const getContractDetail = async (id: any) => {
    const { data } = await getContractDetailsApi(id);
    contractDetail.value = data;
};

/** 撤销审核 */
const revokeExamine = async (id: any)=>{
    await revokeExamineApi(id);
};

/** 合同完结 */
const handleCurrentChange = (val: any) => {
    currentRow.value = val;
};

const handleClickAdd = ()=>{
    addDialogVisible.value = true;
};

const handleSubmitAdd = (result: boolean)=>{
    if(result){
        getContracts();
    }
};

const handleCancelAdd = ()=>{
    addDialogVisible.value = false;
};

/** 编辑合同 */
const handleClickEdit = (row: contractVo)=>{
    if(row.approvalStatus == '0'){
        editData.value = row;
        editDialogVisible.value = true;
    }else{
        proxy?.$modal.msgWarning('该合同已被审批，无法编辑');
    };
};

const handleSubmitEdit = (result: boolean)=>{
    if(result){
        getContracts();
    };
};

const handleCancelEdit = ()=>{
    editDialogVisible.value = false;
};

/** 删除合同 */
const handleClickDelete = async (row: contractVo)=>{
    await proxy?.$modal.confirm('确认删除合同?');
    const result = await deleteContractApi(row.id);
    if(result.code == 200){
        proxy?.$modal.msgSuccess("删除成功");
        getContracts();
    };
};

/** 点击查看合同详情 */
const handleClickCheck = (row: contractVo)=>{
    getContractDetail(row?.id).then((result)=>{
        checkDialogVisible.value = true;
    }); 
};

const handleCancelCheck = ()=>{
    checkDialogVisible.value = false;
};

/** 合同完结 */
const handleClickComplete = async (row: contractVo)=>{
    if(row.overFlag !== '0'){
        proxy?.$modal.msgWarning("该合同已完结");
    }else{
        await proxy?.$modal.confirm(`该合同还有定金${(row?.contractDeposit || 0) - (row?.depositAlreadyPaid || 0)}未使用，确认要完结么?`);
        const completeData = {
            id: row.id,
            overFlag: '1'
        }
        await completeContractDetailsApi(completeData);
    };
    
};

/** 退还定金申请 */
const handleClickRefund = (row: contractVo)=>{
    getContractDetail(row?.id).then((result)=>{
        refundDialogVisible.value = true;
    });
};

const handleSubmitRefund = (result: boolean)=>{
    if(result){
        getContracts();
    }
};

const handleCancelRefund = ()=>{
    refundDialogVisible.value = false;
};

/** 销售审核 */
const handleClickexamine = (row:any)=>{
    if(row.reviewStatus !== '2'){
        getContractDetail(row?.id).then((result)=>{
            examineDialogVisible.value = true;
        });
        /** todo */
    }else{
        proxy?.$modal.msgWarning("该合同已被审批拒绝");
    };
};

const handleSubmitExamine = (result: boolean)=>{
    if(result){
        getContracts();
    }
};

const handleCancelexamine = ()=>{
    examineDialogVisible.value = false;
};

/** 销售审核 */
const handleClickFinance = async (row:any)=>{
    getContractDetail(row?.id).then((result)=>{
        financeDialogVisible.value = true;
    });
};

const handleSbumitFinance = (result: boolean) => {
    if(result){
        getContracts();
    }
};

const handleCancelFinance = ()=>{
    financeDialogVisible.value = false;
};

/** 审批合同 */
const handleClickApproval = (row: contractVo)=>{
    if(row.approvalStatus !== '0'){
        proxy?.$modal.msgWarning("该合同已审批");
    }else{
        getContractDetail(row?.id).then((result)=>{
            approvalDialogVisible.value = true;
        });
    };
};

const handleSubmitApproval = (result:boolean)=>{
    if(result){
        getContracts();
    }
};

const handleCancelApproval = ()=>{
    approvalDialogVisible.value = false;
};

/** 点击撤销审核 */
const handleClickRevoke = async (row: contractVo)=>{
    const isManager = store.roleNames.includes('总经理');
    const isAdmin = store.roleNames.includes('超级管理员');
    if(isManager || isAdmin){
        //是总经理或超级管理员，可以撤销所有阶段
        await proxy?.$modal.confirm('确认撤销审核的合同?');
        revokeExamine(row.id);
    }else if(!isManager && !isAdmin && row.reviewStatus !== '1'){
        //不是总经理，只能撤销销售审核的
        proxy?.$modal.msgWarning("业务员只能撤销销售审核的合同");
    }else if(!isManager && !isAdmin && row.reviewStatus == '1'){
        // 业务员能撤销销售审核的合同
        await proxy?.$modal.confirm('确认撤销审核的合同?');
    };
};

/** 撤销审批 */
const handleRevokeApprove = async (row: contractVo)=>{
    if(row.approvalStatus !== '0'){
        await proxy?.$modal.confirm('确认撤销审批的合同？');
        const submitData = {
            contractId: row.id,
            approvalStatus: 0,
            type: 1
        };
        await approveContractDetailsApi(submitData).then(result=>{
            if(result.code == 200){
                getContracts();
            }
        })
    }else{
        proxy?.$modal.msgWarning("该合同未提交审批或已被拒绝");
    }
};

onMounted(()=>{
    getCustomers();
    getContracts();
    getUserListByRoleKey('business_role');
});

</script>

<style lang="scss" scoped>
.header-button-container{
    display: flex;
    align-items: center;
}
.contract-info{
    font-weight: bold;
}
.approved{
    color: green;
}
.unapproved{
    color: blue;
}
.unapproved-reject{
    color: red;
}
.deduction-none{
    color: red;
}
.deduction-part{
    color: orange;
}
.deduction-all{
    color:green;
}
.completed{
    color: green;
}
.uncompleted{
    color: red;
}
.examined-saler{
    color:green;
}
examined-finance{
    color: blue;
}
.unexamined{
    color: red;
}
.operation{
    display: flex;
    flex-wrap: wrap;
}
</style>